/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.beepmystuff;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;

/**
 * An implementation of SimpleCursorAdapter which binds BeepMyStuff item
 * entries to the item.xml layout, including decoding the image and setting
 * it as a bitmap.
 */
public class ScanRegistryAdapter extends SimpleCursorAdapter {
  public ScanRegistryAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
  }

  @Override
  public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);
    ImageView imageView = (ImageView) view.findViewById(R.id.item_image);
    int imageIndex = cursor.getColumnIndexOrThrow(ScanRegistry.FIELD_IMAGE_DATA);
    byte[] data = cursor.getBlob(imageIndex);
    if (data != null) {
      Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
      imageView.setImageBitmap(bm);
    } else {
      int stateIndex = cursor.getColumnIndexOrThrow(ScanRegistry.FIELD_STATE);
      int state = cursor.getInt(stateIndex);
      if (ScanRegistry.isStatePendingImage(state)) {
        imageView.setImageResource(R.drawable.waiting);
      } else {
        imageView.setImageResource(R.drawable.error);
      }
    }
  }
}
